import pymysql
from todo1 import Todo
class todo:
    @staticmethod
    def get_connection():
        return pymysql.Connection(host="192.168.171.128",database='test02',user='root',password='root@123ABC',autocommit=True)
    def init_db(self):
        with self.get_connection() as conn:
            create_todos=('''
                create table if not exists todos(
                todo_id int not null PRIMARY key auto_increment,
                title varchar(55) not null default '',
                completed int not null default '0'
            )
            ''')
            cursor=conn.cursor()
            cursor.execute(create_todos)
    def create(self,title:str):
        with self.get_connection() as conn:
            cursor=conn.cursor()
            cursor.execute("insert into todos(title) values(%s)",(title,))
            cursor.execute('select last_insert_id()')
            (todo_id)=cursor.fetchall()
            print(todo_id)
            return Todo(title)
    def cover_row_to_object(self,x):
        return Todo(x[1],id=x[0],completed=True if x[2]==1 else False)
    def get_list(self):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('select* from todos')
            date=cursor.fetchall()
            todo_list=[]
            for x in date:
                todo_list.append(self.cover_row_to_object(x))
            return todo_list
    def get_todo_by_id(self,todo_id):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("select * from todos where todo_id=%s",(todo_id,))
            date=cursor.fetchone()
            print(date)
            if date is not None:
                return self.cover_row_to_object(date)
            else:
                return False
    def mark_completed(self,todo_id):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("update todos set completed=1 where todo_id=%s",(todo_id,))
            return self.get_todo_by_id(todo_id)
    def del_todo(self,title):
        with self.get_connection() as conn:
            cursor = conn.cursor()
            for x in self.get_list():
                if x.title == title:
                    cursor.execute("delete from todos where title=%s",(title,))
                    return x
                else:
                    return False






t=todo()
t.init_db()
# t.create('t1')
# #t.cover_row_to_object()
# #rint(t.get_list())
# #t.get_todo_by_id(1)
# # print(t.mark_completed(3))
# # print(t.del_todo("学习dak"))
# print(t.get_todo_by_id(1))
print(t.del_todo('t6'))

